package com.zs.studentmanager.utils;

import com.zs.studentmanager.exception.CustomException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author: 周小白
 * @date: 2024-01-27 08:39
 **/
public class UploadUtil {




    /**
     * 上传文件
     * @param file 文件
     * @param path 文件路径
     * @return 文件名
     */
    public static String uploadFile(MultipartFile file, String path) {
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = "";
        if (originalFilename != null) {
            suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        // 获取文件大小
        long size = file.getSize();

        if (".png".equals(suffixName) || ".jpg".equals(suffixName) || ".jpeg".equals(suffixName) || ".gif".equals(suffixName)) {
            File folder = new File(path);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }

            String newName = System.currentTimeMillis() + suffixName;

            try {
                file.transferTo(new File(folder, newName));
            } catch (Exception e) {
                throw new CustomException(e.getMessage());
            }

            return newName;
        }else {
            return null;
        }
    }
}
